package com.xpjhs.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;





import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;

import com.xpjhs.user.dao.UserDao;
import com.xpjhs.user.model.User;

public class ImportExcel {
	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	private UserDao userDao;

	public void read(InputStream inputStream) throws IOException {
		// 初始化整个Excel
		HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
		// 循环workbook内的所有sheet
		for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
			HSSFSheet sheet = workbook.getSheetAt(sheetIndex);
			System.err.println("sheet序号:" + sheetIndex + "\nsheet名称："
					+ sheet.getSheetName());
			// 循环该sheet表中的每一行
			for (int rowIndex = 1; rowIndex < sheet.getLastRowNum(); rowIndex++) {
				HSSFRow row = sheet.getRow(rowIndex);
				if (row == null) {
					continue;
				}
				HSSFCell cell0 = row.getCell(0);
				String qq = "";
				String realname = "";
				String email = "";
				if (cell0 != null) {

					cell0.setCellType(cell0.CELL_TYPE_STRING);
					qq = cell0.getRichStringCellValue().toString();
				}
				HSSFCell cell1 = row.getCell(1);
				if (cell1 != null) {

					cell1.setCellType(cell1.CELL_TYPE_STRING);
					realname = cell1.getRichStringCellValue().toString();
				}
				HSSFCell cell2 = row.getCell(2);
				if (cell2 != null) {

					cell2.setCellType(cell2.CELL_TYPE_STRING);
					email = cell2.getRichStringCellValue().toString();
				}
				User user = new User();
				user.setEmail(email);
				user.setUsername(qq);
				user.setRealName(realname);
				userDao.save(user);
			}
			System.out.println("-------success!!!----------");
		}
	}
}
